#!/usr/bin/env python

import urllib2, urllib, json, time
from random import choice



#Get probes
#---------------------------------------------------------------------------------------------
#Get data from RIPE ATlas REST
response = urllib.urlopen("https://atlas.ripe.net/api/v1/probe/?fields=status,id,country_code,prefix_v4,asn_v4&limit=7700")
jsondata = json.loads(response.read())
(true,false,null) = (True,False,None)
result = eval(str(jsondata))
#Save only live probes
probe = [i for i in result.get("objects") if i.get("status") == 1]

#Retain only probes from unique prefixes by creating a dict with prefixes as keys. This will ultimately drop every >1 insertion with the same key
probeDict = {}
for i in probe:
    if i.get("prefix_v4") and i.get("asn_v4"):
        probeDict[i.get("prefix_v4")] = [i.get("id"), i.get("asn_v4")]
#Remove probes from RIPE NCC's ASNs
ripeASNs = [2121,3333,12654,12898,34964,196615]
keysToRemove = [k for k,v in probeDict.items() if int(v[1]) in ripeASNs]
for key in keysToRemove:
    if key in probeDict.keys():
        del probeDict[key]
#Retain only probe IDs
probe = [v[0] for v in probeDict.values()]
#Order probes within lists of size <=500. Required due to limitation in atlas UDM
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
probe = lol(probe, 500)
#---------------------------------------------------------------------------------------------


#Schedule measurement from each probe
#The measurement has the following properties:
#separate measurement for each ~500 hosts in the network
#intensity: 22 minutes
#duration: 24 hours
#Packets p/mm: 3
#packet size: 48
#
#
#Also launches a control ping towards Routing Beacon RRC3 AMS-IX
#intensity: 55.11 minutes
#duration: 24 hours
#Packets p/mm: 3
#packet size: 48

#target = {#"128.0.0.0/16"  :"128.0.144.145",
#           "185.1.0.0/21"  :"185.1.1.1",
#         }# "185.1.24.0/24 ":"185.24.0.1"}
         
print probe
"""
for prefix in target.keys():
        #Base Restful API requirements
        key = "20cf1905-41c9-4e3d-b83f-93c06769caa7"
        url = "https://atlas.ripe.net/api/v1/measurement/?key=%s" % key
        request = urllib2.Request(url)
        request.add_header("Content-Type", "application/json")
        request.add_header("Accept", "application/json")
        chunkID=0
        for chunk in probe:
                data = { "definitions": 
                         [
                           { 
                             "af": "4",
                             "type": "ping",
                             "target": target.get(prefix),
                             "packets":3,
                             "size": 48,
                             "interval": 1320,
                             "is_oneoff": False,
                             "is_public": True,
                             "description": ""#"Debogon "+prefix+" with reference point 84.205.83.1 chunk"+str(chunkID)
                           },
                           { 
                             "af": "4",
                             "type": "ping",
                             "target": "84.205.83.1",
                             "packets":3,
                             "size": 48,
                             "interval": 3307,
                             "is_oneoff": False,
                             "is_public": True,
                             "description": ""#"Debogon "+prefix+" reference point chunk"+str(chunkID)
                           } 
                         ],
                         "probes":
                         [
                           {
                             'requested': '500', 
                             'type': 'probes', 
                             'value': ",".join(str(v) for v in sorted(chunk))
                           }
                         ],
                         #"start_time": str(int(time.time())),
                         #"stop_time": "1391032800"
                       }
                try: conn = urllib2.urlopen(request, json.dumps(data))
                except urllib2.URLError, e:
                    print e.reason
                chunkID=chunkID+1
                #time.sleep(20)
"""
